/**
 * 该文件可自行根据业务逻辑进行调整
 */
import type { RequestClientOptions } from '@vben/request';

import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import {
  authenticateResponseInterceptor,
  defaultResponseInterceptor,
  errorMessageResponseInterceptor,
  RequestClient,
} from '@vben/request';
import { useAccessStore } from '@vben/stores';

import { message } from 'ant-design-vue';

import { useAuthStore } from '#/store';

import { refreshTokenApi } from './core';

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

function createRequestClient(baseURL: string, options?: RequestClientOptions) {
  const client = new RequestClient({
    ...options,
    baseURL,
  });

  /**
   * 重新认证逻辑
   */
  async function doReAuthenticate() {
    const accessStore = useAccessStore();
    const authStore = useAuthStore();
    accessStore.setAccessToken(null);
    await authStore.logout();
  }

  /**
   * 刷新token逻辑
   */
  async function doRefreshToken() {
    const accessStore = useAccessStore();
    const resp = await refreshTokenApi();
    const newToken = resp.data;
    accessStore.setAccessToken(newToken);
    return newToken;
  }

  function formatToken(token: null | string) {
    return token ? `Bearer ${token}` : null;
  }

  // 请求头处理
  client.addRequestInterceptor({
    fulfilled: async (config) => {
      const accessStore = useAccessStore();

      config.headers.Authorization = formatToken(accessStore.accessToken);
      config.headers['Accept-Language'] = preferences.app.locale;
      return config;
    },
  });

  // 添加调试日志
  client.addResponseInterceptor({
    fulfilled: (response) => {
      return response;
    },
  });

  // 添加自定义响应拦截器，处理业务逻辑错误
  client.addResponseInterceptor({
    fulfilled: (response) => {
      const { config, data: responseData } = response;

      // 如果不是body响应或者响应数据不是对象，则直接返回
      if (
        config.responseReturn !== 'body' ||
        !responseData ||
        typeof responseData !== 'object'
      ) {
        return response;
      }

      // 检查业务状态码，只有code为200时才视为成功
      if (
        (responseData.code !== undefined && responseData.code !== 200) ||
        responseData.success === false
      ) {
        // 创建错误对象，使用接口返回的错误信息
        const error = new Error(responseData.message || '请求失败');
        // 附加额外信息，方便错误处理
        Object.assign(error, {
          response,
          config,
          businessCode: responseData.code,
          businessData: responseData.data,
          isBusinessError: true,
          originalMessage: responseData.message,
        });
        // 抛出错误，会被后续的错误处理拦截器捕获
        throw error;
      }
      return response;
    },
  });

  // 处理返回的响应数据格式
  client.addResponseInterceptor(
    defaultResponseInterceptor({
      codeField: 'code',
      dataField: 'data',
      successCode: 200,
    }),
  );

  // token过期的处理
  client.addResponseInterceptor(
    authenticateResponseInterceptor({
      client,
      doReAuthenticate,
      doRefreshToken,
      enableRefreshToken: false,
      formatToken,
    }),
  );

  // 通用的错误处理,如果没有进入上面的错误处理逻辑，就会进入这里
  client.addResponseInterceptor(
    errorMessageResponseInterceptor((msg: string, error) => {
      // 优先处理业务错误
      if (error && error.isBusinessError) {
        // 直接使用错误对象中保存的原始错误消息
        const errorMessage =
          error.originalMessage || error.message || '请求失败';
        message.error(errorMessage);
        return;
      }

      // 处理HTTP错误
      if (error && error.response) {
        // 尝试从响应中获取错误信息
        let errorMsg = msg;
        try {
          const responseData = error.response.data;
          if (responseData && responseData.message) {
            errorMsg = responseData.message;
          }
        } catch (error_) {
          console.error('解析响应错误信息失败:', error_);
        }

        message.error(errorMsg);
        return;
      }

      // 处理网络错误、超时等其他错误
      message.error(msg || '网络异常，请稍后重试');
    }),
  );

  return client;
}

export const requestClient = createRequestClient(apiURL, {
  responseReturn: 'body',
});

export const baseRequestClient = new RequestClient({ baseURL: apiURL });
